<template>
  <div id="login" class="container">
    <el-form
      class="form"
      label-position="right"
      label-width="100px"
      style="max-width: 460px"
    >
      <el-form-item label="用户名">
        <el-input
          class="input"
          type="text"
          v-model="formData.username"
          minlength='6'
          autocomplete
          placeholder="请输入账号"
        />
      </el-form-item>
      <el-form-item label="密码">
        <el-input
          class="input"
          type="password"
          show-password
          minlength='6'
          v-model="formData.password"
          placeholder="请输入密码"
        />
      </el-form-item>
      <el-form-item>
        <el-button class="login" type="success" @click="login">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive } from 'vue'
import { ElMessage, ElLoading } from 'element-plus'
import cache from '@/utils/cache'
import http from '@/http/http'
import router from '@/router/index'
const data = reactive({
  background: 'linear-gradient(#66ccff, #39c5bb)'
})
const formData = reactive({
  username: '',
  password: ''
})
const login = () => {
  if (!formData.username) {
    ElMessage.error('请输入用户名')
    return
  } else if (formData.username.length < 6) {
    ElMessage.error('用户名格式错误')
    return
  } else if (!formData.password) {
    ElMessage.error('请输入密码')
    return
  } else if (formData.password.length < 6) {
    ElMessage.error('密码格式错误')
    return
  }
  const loading = ElLoading.service({
    target: '#login'
  })
  http.request({
    method: 'POST',
    url: '/Admin/login',
    data: {
      username: formData.username,
      password: formData.password
    }
  }).then((res) => {
    if (res.status === 200) {
      cache.cache('token', res.data.token)
      cache.cache('name', res.data.name)
      cache.cache('avatar', res.data.avatar)
      router.replace({ name: 'admin' })
      loading.close()
    }
  })
}
const getBackground = () => {
  const url = '/Admin/bingImg'
  http.request({
    url: url,
    method: 'GET'
  }).then((res) => {
    if (res.status === 200) {
      data.background = 'url(' + res.data + ')' + ',' + data.background
    }
  })
}
onMounted(() => {
  getBackground()
})
</script>

<style scoped lang='scss'>
.container {
  width: 100%;
  height: 100%;
  background-image: v-bind('data.background');
}
.form {
  width: 800px;
  height: 200px;
  background: rgba(230,230,230,0.8);
  padding: 50px 0 0 0;
  box-sizing: border-box;
  position: absolute;
  bottom: 30%;
  right: 10%;
}
.input {
  width: 80%;
}
.login {
  width: 80%;
}
</style>
